<template>
    <div class="course-manage">
        <div class="page-header">
            <h2>课程管理</h2>
            <div class="header-actions">
                <el-button type="primary" @click="handleAdd">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    添加课程
                </el-button>
                <el-button type="danger" :disabled="!selectedCourses.length" @click="handleBatchDelete">
                    <el-icon>
                        <Delete />
                    </el-icon>
                    批量删除
                </el-button>
            </div>
        </div>

        <!-- 搜索筛选区域 -->
        <div class="filter-container">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="课程名称">
                    <el-input v-model="searchForm.name" placeholder="请输入课程名称" clearable />
                </el-form-item>
                <el-form-item label="课程编号">
                    <el-input v-model="searchForm.courseCode" placeholder="请输入课程编号" clearable />
                </el-form-item>
                <el-form-item label="课程类型">
                    <el-select v-model="searchForm.type" placeholder="请选择课程类型" clearable>
                        <el-option v-for="item in courseTypeOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="开课院系">
                    <el-select v-model="searchForm.department" placeholder="请选择开课院系" clearable>
                        <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">
                        <el-icon>
                            <Search />
                        </el-icon>
                        搜索
                    </el-button>
                    <el-button @click="handleReset">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                        重置
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 表格区域 -->
        <div class="table-container">
            <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange"
                v-loading="loading">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="courseCode" label="课程编号" width="120" />
                <el-table-column prop="name" label="课程名称" width="180" />
                <el-table-column prop="type" label="课程类型" width="120">
                    <template #default="scope">
                        <el-tag :type="getCourseTypeTag(scope.row.type)">
                            {{ scope.row.type }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="credit" label="学分" width="80" />
                <el-table-column prop="hours" label="学时" width="80" />
                <el-table-column prop="department" label="开课院系" width="120" />
                <el-table-column prop="teacher" label="授课教师" width="120" />
                <el-table-column prop="capacity" label="容量" width="80" />
                <el-table-column prop="enrolled" label="已选" width="80">
                    <template #default="scope">
                        <el-progress :percentage="getEnrollPercentage(scope.row)"
                            :color="getProgressColor(scope.row)" />
                    </template>
                </el-table-column>
                <el-table-column prop="semester" label="开课学期" width="120" />
                <el-table-column label="操作" width="160" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                            编辑
                        </el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 添加/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="right">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="课程编号" prop="courseCode">
                            <el-input v-model="form.courseCode" :disabled="isEdit" placeholder="请输入课程编号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="课程名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入课程名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="课程类型" prop="type">
                            <el-select v-model="form.type" placeholder="请选择课程类型" style="width: 100%">
                                <el-option v-for="item in courseTypeOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开课院系" prop="department">
                            <el-select v-model="form.department" placeholder="请选择开课院系" style="width: 100%">
                                <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="学分" prop="credit">
                            <el-input-number v-model="form.credit" :min="0.5" :max="10" :step="0.5" placeholder="请输入学分"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="学时" prop="hours">
                            <el-input-number v-model="form.hours" :min="8" :max="200" :step="8" placeholder="请输入学时"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="容量" prop="capacity">
                            <el-input-number v-model="form.capacity" :min="1" :max="500" placeholder="请输入容量"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="授课教师" prop="teacher">
                            <el-select v-model="form.teacher" placeholder="请选择授课教师" style="width: 100%" filterable>
                                <el-option v-for="item in teacherOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开课学期" prop="semester">
                            <el-select v-model="form.semester" placeholder="请选择开课学期" style="width: 100%">
                                <el-option v-for="item in semesterOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="上课时间" prop="schedule">
                    <el-input v-model="form.schedule" placeholder="请输入上课时间，如：周一 1-2节" />
                </el-form-item>
                <el-form-item label="上课地点" prop="location">
                    <el-input v-model="form.location" placeholder="请输入上课地点" />
                </el-form-item>
                <el-form-item label="课程简介" prop="description">
                    <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入课程简介" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        {{ isEdit ? '更新' : '添加' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete, Edit, Search, Refresh } from '@element-plus/icons-vue';
import {
    getCourseList,
    addCourse,
    updateCourse,
    deleteCourse,
    batchDeleteCourses,
    getCourseTypeList,
    getDepartmentList,
    getTeacherList
} from '@/api/course';

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const selectedCourses = ref([]);

// 搜索表单
const searchForm = reactive({
    name: '',
    courseCode: '',
    type: '',
    department: ''
});

// 分页
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
});

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('');
const isEdit = ref(false);
const submitLoading = ref(false);

// 表单
const formRef = ref(null);
const form = reactive({
    courseCode: '',
    name: '',
    type: '',
    credit: 2,
    hours: 32,
    department: '',
    teacher: '',
    capacity: 50,
    enrolled: 0,
    semester: '',
    schedule: '',
    location: '',
    description: ''
});

// 表单验证规则
const rules = {
    courseCode: [
        { required: true, message: '请输入课程编号', trigger: 'blur' },
        { pattern: /^[A-Z]{2,4}\d{4,6}$/, message: '课程编号格式不正确，如：CS1001', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入课程名称', trigger: 'blur' },
        { min: 2, max: 30, message: '课程名称长度在2-30个字符', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择课程类型', trigger: 'change' }
    ],
    credit: [
        { required: true, message: '请输入学分', trigger: 'blur' },
        { type: 'number', min: 0.5, max: 10, message: '学分在0.5-10之间', trigger: 'blur' }
    ],
    hours: [
        { required: true, message: '请输入学时', trigger: 'blur' },
        { type: 'number', min: 8, max: 200, message: '学时在8-200之间', trigger: 'blur' }
    ],
    department: [
        { required: true, message: '请选择开课院系', trigger: 'change' }
    ],
    teacher: [
        { required: true, message: '请选择授课教师', trigger: 'change' }
    ],
    capacity: [
        { required: true, message: '请输入容量', trigger: 'blur' },
        { type: 'number', min: 1, max: 500, message: '容量在1-500之间', trigger: 'blur' }
    ],
    semester: [
        { required: true, message: '请选择开课学期', trigger: 'change' }
    ],
    schedule: [
        { required: true, message: '请输入上课时间', trigger: 'blur' }
    ],
    location: [
        { required: true, message: '请输入上课地点', trigger: 'blur' }
    ]
};

// 课程类型选项
const courseTypeOptions = [
    { value: '必修课', label: '必修课' },
    { value: '选修课', label: '选修课' },
    { value: '专业选修', label: '专业选修' },
    { value: '通识教育', label: '通识教育' },
    { value: '实验课', label: '实验课' }
];

// 获取课程类型标签颜色
const getCourseTypeTag = (type) => {
    const typeMap = {
        '必修课': 'danger',
        '选修课': 'primary',
        '专业选修': 'warning',
        '通识教育': 'success',
        '实验课': 'info'
    };
    return typeMap[type] || 'primary';
};

// 院系选项
const departmentOptions = [
    { value: '计算机学院', label: '计算机学院' },
    { value: '数学学院', label: '数学学院' },
    { value: '物理学院', label: '物理学院' },
    { value: '化学学院', label: '化学学院' },
    { value: '文学院', label: '文学院' },
    { value: '外语学院', label: '外语学院' },
    { value: '经济学院', label: '经济学院' },
    { value: '管理学院', label: '管理学院' }
];

// 教师选项
const teacherOptions = [
    { value: '张老师', label: '张老师' },
    { value: '李老师', label: '李老师' },
    { value: '王老师', label: '王老师' },
    { value: '刘老师', label: '刘老师' },
    { value: '陈老师', label: '陈老师' }
];

// 学期选项
const semesterOptions = [
    { value: '2023-2024-1', label: '2023-2024学年第一学期' },
    { value: '2023-2024-2', label: '2023-2024学年第二学期' },
    { value: '2024-2025-1', label: '2024-2025学年第一学期' },
    { value: '2024-2025-2', label: '2024-2025学年第二学期' }
];

// 获取选课百分比
const getEnrollPercentage = (row) => {
    if (!row.capacity || row.capacity === 0) return 0;
    return Math.round((row.enrolled / row.capacity) * 100);
};

// 获取进度条颜色
const getProgressColor = (row) => {
    const percentage = getEnrollPercentage(row);
    if (percentage >= 90) return '#f56c6c';
    if (percentage >= 70) return '#e6a23c';
    return '#67c23a';
};

// 获取课程类型列表数据
const fetchCourseTypeData = async () => {
    try {
        const response = await getCourseTypeList();
        if (response.data && response.data.length > 0) {
            courseTypeOptions.splice(0, courseTypeOptions.length, ...response.data);
        }
    } catch (error) {
        console.error('获取课程类型列表失败:', error);
    }
};

// 获取院系列表数据
const fetchDepartmentData = async () => {
    try {
        const response = await getDepartmentList();
        if (response.data && response.data.length > 0) {
            departmentOptions.splice(0, departmentOptions.length, ...response.data);
        }
    } catch (error) {
        console.error('获取院系列表失败:', error);
    }
};

// 获取教师列表数据
const fetchTeacherData = async () => {
    try {
        const response = await getTeacherList();
        if (response.data && response.data.length > 0) {
            teacherOptions.splice(0, teacherOptions.length, ...response.data);
        }
    } catch (error) {
        console.error('获取教师列表失败:', error);
    }
};

// 获取课程列表
const getCourseListData = async () => {
    loading.value = true;
    try {
        // 构建查询参数
        const params = {
            page: pagination.currentPage,
            size: pagination.pageSize,
            name: searchForm.name,
            courseCode: searchForm.courseCode,
            type: searchForm.type,
            department: searchForm.department
        };

        // 调用API获取数据
        const response = await getCourseList(params);

        // 更新表格数据和分页信息
        tableData.value = response.data.list || [];
        pagination.total = response.data.total || 0;

    } catch (error) {
        console.error('获取课程列表失败:', error);
        ElMessage.error('获取课程列表失败');
        // 清空数据
        tableData.value = [];
        pagination.total = 0;
    } finally {
        loading.value = false;
    }
};

// 搜索
const handleSearch = () => {
    pagination.currentPage = 1;
    getCourseListData();
};

// 重置搜索
const handleReset = () => {
    searchForm.name = '';
    searchForm.courseCode = '';
    searchForm.type = '';
    searchForm.department = '';
    handleSearch();
};

// 表格选择变化
const handleSelectionChange = (selection) => {
    selectedCourses.value = selection;
};

// 分页大小变化
const handleSizeChange = (size) => {
    pagination.pageSize = size;
    getCourseListData();
};

// 当前页变化
const handleCurrentChange = (page) => {
    pagination.currentPage = page;
    getCourseListData();
};

// 添加课程
const handleAdd = () => {
    dialogTitle.value = '添加课程';
    isEdit.value = false;
    dialogVisible.value = true;
    // 重置表单
    Object.keys(form).forEach(key => {
        if (key === 'credit') {
            form[key] = 2;
        } else if (key === 'hours') {
            form[key] = 32;
        } else if (key === 'capacity') {
            form[key] = 50;
        } else if (key === 'enrolled') {
            form[key] = 0;
        } else {
            form[key] = '';
        }
    });
};

// 编辑课程
const handleEdit = (row) => {
    dialogTitle.value = '编辑课程';
    isEdit.value = true;
    dialogVisible.value = true;
    // 填充表单数据
    Object.keys(form).forEach(key => {
        form[key] = row[key];
    });
};

// 删除课程
const handleDelete = (row) => {
    ElMessageBox.confirm(`确定要删除课程 ${row.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            // 调用API删除数据
            await deleteCourse(row.courseCode);
            ElMessage.success('删除成功');
            getCourseListData();
        } catch (error) {
            console.error('删除失败:', error);
            ElMessage.error('删除失败');
        }
    }).catch(() => {
        // 用户取消删除
    });
};

// 批量删除
const handleBatchDelete = () => {
    if (selectedCourses.value.length === 0) {
        ElMessage.warning('请选择要删除的课程');
        return;
    }

    ElMessageBox.confirm(`确定要删除选中的 ${selectedCourses.value.length} 门课程吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            // 获取选中的课程ID列表
            const ids = selectedCourses.value.map(item => item.courseCode);

            // 调用API批量删除数据
            await batchDeleteCourses(ids);
            ElMessage.success('批量删除成功');
            getCourseListData();
        } catch (error) {
            console.error('批量删除失败:', error);
            ElMessage.error('批量删除失败');
        }
    }).catch(() => {
        // 用户取消删除
    });
};

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return;

    try {
        await formRef.value.validate();
        submitLoading.value = true;

        if (isEdit.value) {
            // 调用API更新数据
            await updateCourse(form.courseCode, form);
            ElMessage.success('更新成功');
        } else {
            // 调用API添加数据
            await addCourse(form);
            ElMessage.success('添加成功');
        }

        dialogVisible.value = false;
        getCourseListData();
    } catch (error) {
        console.error('表单验证失败或提交失败:', error);
        if (error.response && error.response.data && error.response.data.message) {
            ElMessage.error(error.response.data.message);
        } else if (!error.name || error.name !== 'ElMessageBox') {
            // 开发环境下静默处理
            if (!import.meta.env.DEV) {
                ElMessage.error(isEdit.value ? '更新失败' : '添加失败');
            } else {
                ElMessage.success(isEdit.value ? '模拟更新成功' : '模拟添加成功');
                dialogVisible.value = false;

                // 开发环境下模拟更新或添加到列表
                if (isEdit.value) {
                    // 更新现有项
                    const index = tableData.value.findIndex(item => item.courseCode === form.courseCode);
                    if (index !== -1) {
                        tableData.value[index] = { ...form };
                    }
                } else {
                    // 添加新项
                    tableData.value.unshift({ ...form, enrolled: 0 });
                    pagination.total++;
                }
            }
        }
    } finally {
        submitLoading.value = false;
    }
};

// 初始化
onMounted(async () => {
    // 加载课程类型、院系和教师数据
    await Promise.all([fetchCourseTypeData(), fetchDepartmentData(), fetchTeacherData()]);
    // 获取课程列表
    getCourseListData();
});
</script>

<style scoped>
.course-manage {
    padding: 15px;
    background-color: #f0f2f5;
    min-height: calc(100vh - 60px);
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding: 0 5px;
}

.header-actions {
    display: flex;
    gap: 10px;
}

.filter-container {
    background-color: #fff;
    padding: 12px;
    border-radius: 4px;
    margin-bottom: 15px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form .el-form-item {
    margin-bottom: 0;
}

.table-container {
    background-color: #fff;
    padding: 12px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .course-manage {
        padding: 10px;
    }

    .page-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }

    .header-actions {
        width: 100%;
        justify-content: flex-start;
    }

    .search-form {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
    }
}
</style>